package com.hermes.comics.extractors;

import android.text.TextUtils;

import com.hermes.comics.data.Issue;
import com.hermes.comics.data.Serie;

import java.util.ArrayList;
import java.util.List;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class WebExtractor {

  private final String content;
  private final String url;

  public WebExtractor(String url, String content) {
    this.content = cleanContent(content);
    this.url = url.replace("&amp;", "&");
  }

  public List<String> extractUrls() {
    return new ArrayList<String>();
  }

  public String getUrl() {
    return url;
  }

  public String getContent() {
    return content;
  }

  public abstract boolean extractSerie(Serie serie);

  public abstract boolean extractIssue(Issue issue);

  protected List<String> matchAll(String content, Pattern pattern) {
    List<String> result = new ArrayList<String>();

    if (TextUtils.isEmpty(content)) return result;

    Matcher matcher = pattern.matcher(content);
    while (matcher.find()) {
      result.add(matcher.group(1).trim());
    }

    return result;
  }

  protected String match(String content, Pattern pattern) {
    Matcher matcher = pattern.matcher(content);
    return matcher.find() ? matcher.group(1).replaceAll("\\s+", " ").trim() : null;
  }

  private String cleanContent(String content) {
    return content.replace("&nbsp;", " ")
        .replace("&ordf;", "a")
        .replace("&deg;", "o");
  }
}
